<script setup lang="ts">
import { useStorage } from '@vueuse/core'
interface ISong {
  title: string
  artist: string
  album: string
  url: string
}
// const { data: songs, status } = await useAsyncData<ISong[]>('songs', () => $fetch('/api/song'))
const songs = ref(await fetch('/api/song').then(res => res.json()))
const song = ref<ISong>()
if (songs.value && songs.value?.length > 0) {
  song.value = songs.value[0]
}
// const { data: lyric } = await useAsyncData<string>('lyric', () => $fetch('/api/lyric'))
const lyric = ref(await fetch('/api/lyric').then(res => res.text()))
let lyricArr = null
if (lyric.value) {
  //获取歌词
  lyricArr = lyric.value!.split('\r\n').filter(item=>item).map((item) => {
    const index = item.indexOf(']')
    return [item.substring(1, index), item.substring(index + 1)]
  }) as [string, string][]
}

const songState = reactive({
  currentTime: 0,
  duration: 0,
  isPlay: false,
  volumn:0.5,
  ...song.value
})


function playOrPause() {
  if (songState.isPlay) {
    audio.value?.pause()
  } else {
    audio.value?.play()
  }
  songState.isPlay = !songState.isPlay
}

function changeCurrentTime() {
  audio.value!.currentTime = songState.currentTime
}

function clickSkipBack(){

}

function clickSkipForward(){
  // this.
}

const currentTimeFormat = computed(() => {
  return useDateFormat(songState.currentTime * 1000, 'mm:ss')
})

const durationFormat = computed(() => {
  return useDateFormat(songState.duration * 1000, 'mm:ss').value
})
const audio = useTemplateRef<HTMLAudioElement>('audio')

const currentLyric = computed(() => {
  if (!lyricArr) return ''
  const currentTime = songState.currentTime
  if(currentTime <= getTime(lyricArr[0]![0])) return lyricArr[0]![1]
  if(currentTime>=getTime(lyricArr[lyricArr.length-1]![0]))return lyricArr[lyricArr.length-1]![1]
  for(let index in lyricArr) {
    let num = Number(index) + 1
    const lyricTime = getTime(lyricArr[num]![0])-0.9
    const lastTime =  getTime(lyricArr[num-1]![0])-0.9
    if(lyricTime >= currentTime&&currentTime>=lastTime){
      return lyricArr[num-1]![1]
    }
  }
})

function getTime(time:string){
  const [minutes, rest = '0.0'] = time.split(':') as [string, string]
  const [seconds, hundredths] = rest.split('.') as [string, string]
  const totalSeconds = parseInt(minutes, 10) * 60 + // 分 → 秒
  parseInt(seconds, 10) +      // 秒
  parseInt(hundredths, 10) / 100; // 百分秒 → 秒的小数部分
  return totalSeconds
}

onBeforeUnmount(() => {
  audio.value?.removeEventListener('timeupdate', () => {
    songState.currentTime = audio.value!.currentTime
  })
  audio.value?.removeEventListener('ended', () => {
    songState.isPlay = false
  })
})

const position = ref({x:0,y:0})
if(localStorage.getItem('musicPlayerPosition')){
  position.value = JSON.parse(localStorage.getItem('musicPlayerPosition') as string)
  console.log(localStorage.getItem('musicPlayerPosition'))
}
const musicPlayer = useTemplateRef('musicPlayer')
const MusicStyle = ref<string|null>(null)
useStorage('musicPlayerPosition',position)

const playMode = ref([
  {
    title:'shuffle',
    icon:'i-carbon-shuffle'
  },
  {
    title:'repeat',
    icon:'i-carbon-repeat'
  },
  {
    title:'reapeatOne',
    icon:'i-carbon-repeat-one'
  }
])
let index = ref(0)
function changePlayMode(){
  if(index.value>=playMode.value.length-1){
    index.value = 0
  }else{
    index.value++
  }
}

const volumnIcon = ref({
  1:'i-carbon-volume-up',
  0.5:'i-carbon-volume-down',
  0:'i-carbon-volume-mute'
})

function changeMusicVolumn(){
  audio.value!.volume = songState.volumn
}

let volumeCache = 0

function changeMusicMuted(){
  if(songState.volumn>0){
    volumeCache = songState.volumn
    audio.value!.volume = 0
    songState.volumn = 0
  }else{
    audio.value!.volume = volumeCache
    songState.volumn = volumeCache
    volumeCache = 0
  }
}

const { style } =  useDraggable(musicPlayer,{
  initialValue:{x:position.value.x,y:position.value.y},
  preventDefault:true,
  onEnd:(val)=>{
    position.value.x = val.x
    position.value.y = val.y
  }
})
watch(style,()=>{
  MusicStyle.value = style.value
},{
  immediate:true
})
let observer:IntersectionObserver|null=(null)
onMounted(() => {
  audio.value!.volume = songState.volumn
  audio.value?.addEventListener('timeupdate', () => {
    songState.currentTime = audio.value!.currentTime
  })
  audio.value?.addEventListener('ended', () => {
    songState.isPlay = false
  })
  audio.value?.addEventListener('canplay',()=>{
    songState.duration = audio.value!.duration
  })
  observer = new IntersectionObserver((entries) => {
    entries.forEach((item) => {
     // item 为 IntersectionObserverEntry对象
     // isIntersecting是一个Boolean值，判断目标元素当前是否可见
     if (!item.isIntersecting) {
      const {style} =  useDraggable(musicPlayer,{
        initialValue:{x:0,y:0},
        preventDefault:true,
        onEnd:(val)=>{
          position.value.x = val.x
          position.value.y = val.y
        }
      })
      MusicStyle.value = style.value
     }
   });
  })
  observer.observe(musicPlayer.value!)
})
onBeforeMount(()=>{
  observer?.disconnect()
})
</script>

<template>
  <!--这里是MusicPlayer-->
  <audio ref="audio" v-if="song" :src="'/audio/' + song.url" />
  <div :style="MusicStyle" class='music' fixed z-1 right-0  b="1" w-50 h-70 rounded-md shadow-lg shadow-gray-600
    bg="#f9fafb" 
    b-color="#e5e7eb"
    dark:b-color="stone-900"
    dark:bg="#222"dark:shadow-none>
    <div w-50 h-70 line-height-none>
      <div ref="musicPlayer" cursor-pointer>
        <div h-45 overflow-hidden>
          <img rounded w-35 h-35 mx-auto my-5 object-fill src="/1.image" fill>
        </div>
        <div h-5 line-height-relaxed flex justify-around>
          <div>{{ songState?.title }}</div>
          <div>{{ songState?.artist }}</div>
        </div>
        <div h-5 overflow-hidden>
          <Transition 
            enter-active-class='delay-500 transition-all duration-500 ease-in-out' 
            leave-active-class='transition-all duration-500 ease-in-out' 
            enter-from-class='opacity-0 translate-y-1em'
            leave-to-class='opacity-0 -translate-y-1em'
          >
            <div :key="currentLyric" text-xs h-5 line-height-relaxed text-center>{{ currentLyric }}</div>
          </Transition>
        </div>
      </div>
      <div select-none text-xs h-5 m-1 flex gap-2 items-center justify-around>
        {{ currentTimeFormat }}<input v-model="songState.currentTime" @input="changeCurrentTime" :min="0"
          :max="songState.duration" w-full class="music-player-bar" type="range" cursor-pointer/>{{ durationFormat }}
      </div>
      <div dark:b-color="stone-900" h-8 b-t-1 flex gap-4 justify-center items-center text-xs>
        <div icon-btn @click="changePlayMode" :class="playMode[index]!.icon"></div>
        <div icon-btn :class="'i-carbon:skip-back-filled'" @click="clickSkipBack"></div>
        <div icon-btn :class="!songState.isPlay ? 'i-carbon:play-filled-alt' : 'i-carbon:pause-filled'"
          @click="playOrPause"></div>
        <div icon-btn :class="'i-carbon:skip-forward-filled'" @click="clickSkipForward"></div>
        <div relative overflow-hidden hover:overflow-visible>
          <div icon-btn  :class="volumnIcon[songState.volumn==0?0:songState.volumn>0.5?1:0.5]" @click="changeMusicMuted"/>
          <input v-model="songState.volumn" @input="changeMusicVolumn" :max="1" step="0.01" :min="0" dark:bg='#222' bg="#fff"
            b-1 p-1 left--7 top--10.5 rounded w-18 h-3 class="music-player-bar volumn-bar" absolute type="range" cursor-pointer/>
        </div>
      </div>
      <!--音量图标
          <div>
            <div icon-btn i-carbon:volume-up-filled-alt></div>
            <div icon-btn i-carbon:volume-down-filled-alt></div>
          </div> 
      -->
    </div>
  </div>
</template>
<style scoped>
.music-player-bar {
  -webkit-appearance: none;
  /* 清除默认样式 */
  /* background: transparent; */
  /* 清除默认背景 */
  text-align: center;

  &::-webkit-slider-runnable-track {
    width: 100%;
    height: 0.1rem;
    background: linear-gradient(to right, #c7d2fe, #818cf8 30%, #6366f1 100%);
    border-radius: 1rem;
  }

  &::-moz-range-track {
    width: 100%;
    height: 0.1rem;
    background: linear-gradient(to right, #c7d2fe, #818cf8 30%, #6366f1 100%);
    border-radius: 1rem;
  }

  /* 滑块样式 - Webkit (Chrome, Safari, Edge) */
  &::-webkit-slider-thumb {
    -webkit-appearance: none;
    width: 0.5rem;
    height: 0.5rem;
    background: #fff;
    border: 0.1rem solid #6366f1;
    border-radius: 50%;
    margin-top: -0.2rem;
    cursor: pointer;
    transition: all 0.2s;
    box-shadow: 0 0.1rem 0.1rem rgba(0, 0, 0, 0.1);
  }

  /* 滑块样式 - Firefox */
  &::-moz-range-thumb {
    width: 0.5rem;
    height: 0.5rem;
    background: #fff;
    border: 0.2rem solid #6366f1;
    border-radius: 50%;
    cursor: pointer;
    transition: all 0.2s;
    box-shadow: 0 0.1rem 0.1rem rgba(0, 0, 0, 0.1);
  }

  /* 悬停和聚焦状态 */
  &::-webkit-slider-thumb:hover {
    box-shadow: 0 0.1rem 0.2rem rgba(0, 0, 0, 0.15);
  }

  &::-moz-range-thumb:hover {
    box-shadow: 0 0.1rem 0.2rem rgba(0, 0, 0, 0.15);
  }

  &:focus {
    outline: none;
  }

  &:focus::-webkit-slider-thumb {
    /* box-shadow: 0 0 0 3px rgba(76, 175, 80, 0.2); */
  }

  &:focus::-moz-range-thumb {
    /* box-shadow: 0 0 0 3px rgba(76, 175, 80, 0.2); */
  }
}
.volumn-bar{
  transform: rotate(-90deg);
}
</style>
